<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/11
 * Time: 14:17
 */

namespace Admin\Frontend\Controllers;


use Admin\Models\crm\XhcustContact;
use Admin\Models\crm\XhcustInfo;
use Admin\Models\sys\XhsysEnum;
use Admin\Models\user\XhsysUser;
use Admin\Models\user\XhsysUserpower;
use Helpers\Assets;
use Helpers\Hrm;
use Helpers\HttpClient;
use Helpers\Main;
use Helpers\Template;
use Helpers\User;
use Helpers\UserPower;

class SchoolContactController extends ControllerBase
{

    public static function getEnums()
    {
        return [
            'bCoop' => [0 => '否', 1 => '是'],
            'iType' => [0 => '意向学校', 1 => '合作学校', 2 => '前期接触',3=>'终止合作'],
            'bWelfare' => [0 => '否', 1 => '是'],
            'bAgree' => [0 => '否', 1 => '是'],
            'iLevel' => XhsysEnum::getEnumByNodeName('学校等级'),
            'iGrade' => XhsysEnum::getEnumByNodeName('年级'),
            'iChargeMode' => XhsysEnum::getEnumByNodeName('收费模式'),
            'iUsageMode' => XhsysEnum::getEnumByNodeName('使用模式'),
            'iGroupId' => XhsysEnum::getEnumByNodeName('客户组别'),
            'bDefault' => [0 => '否', 1 => '是'],
            'iContent' => XhsysEnum::getEnumByNodeName('意向内容'),
            'iAidsLevel'=>[1=>'低',2=>'中',3=>'高'],
        ];
    }

    /**
     * 获取其他权限
     *
     * @param $tag
     * @return array|bool
     * @throws \Exception
     * create by dale 20180411
     */
    public function extraPower($tag){
        if(User::isAdmin()){
            return true;
        }
        $deps = User::getExtraPower('dep',$tag);
        $userIds = Hrm::getUserByDepId($deps);
        $newArr = [];
        foreach ($userIds as $ids){
            $newArr =array_merge($newArr,$ids);
        }
        $newArr = array_values(array_filter($newArr));

        return $newArr;
    }



    /**
     * 联系人列表
     *
     * create by dale 20180411
     */
    public function contactAction(){
        if(!UserPower::checkUserPower('School_List_Contact')){
            return $this->sendViewError('没有权限');
        }
        $schoolId = $this->request->getQuery('schoolId');
        $this->view->pick('school_contact/contact');
        Assets::easyUI();
        Assets::select2();
        Assets::importJs('js/school_contact/contact.js');
        Template::exists('XHSchool_Contact', 'list') or die(Main::showMessageModal('配置文件不存在，请先创建！', 109106002));//检查public/template/from/目录下是否都存在template文件夹
        $listButtonArr = $formButtonArr = $listSearchArr = array();
        if (UserPower::checkUserPower('School_List_Contact_Add')) {
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_add', 'text' => '增加', 'icon' => 'fa-plus');
        }
        if (UserPower::checkUserPower('School_List_Contact_Del')) {
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_del', 'text' => '删除', 'icon' => 'fa-trash');
        }
        if (UserPower::checkUserPower('School_List_Contact_Bind')) {
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_bindAccount', 'text' => '绑定账号', 'icon' => 'fa-pencil');
        }
        if (UserPower::checkUserPower('School_List_Contact_Edit')){
            $listButtonArr[] = ['id' => 'bt_list_user_group', 'text' => '设置用户组', 'plain' => 'true', 'icon' => 'fa-pencil'];
        }


        $info = XhcustInfo::findFirst([
            'columns'    => 'iCUId,iSchoolId',
            'conditions' => 'bDelete = 0 AND iSchoolId = :schoolId:',
            'bind'       => ['schoolId' => $schoolId]
        ]);
        $webArr = array(
            'List' => Template::createList('List', 'XHSchool_Contact', [
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
            ]),
        );
        if(!$info){
            return $this->sendViewError('该学校对应的客户不存在');
        }else{
            $webArr['iCUId']  = $info->iCUId;
        }

        $this->view->setVars($webArr);
    }


    /**
     * 联系人表单
     *
     * created by dale 2017/8/10
     */
    public function contactFormAction()
    {
        $id = $this->request->getQuery('icucId', 'string');
        Assets::select2();
        Assets::importMainJs('assets/xh/xhForm.js');
        Assets::importJs('js/school_contact/myMain.js');
        Assets::importMainJs('assets/xh/xhForm.js');
        Assets::importJs('js/school_contact/contactForm.js');
        $this->view->pick('school_contact/contactForm');
        $webArr = [
            'subject' => XhsysEnum::getEnumByNodeName('学科'),
            'grade'   => XhsysEnum::getEnumByNodeName('年级'),
            'duty'    => XhsysEnum::getEnumByNodeName('学校职位')
        ];
        if($id){
            $info = XhcustContact::findFirst($id);
            if(!User::isAdmin()){
                $userId = Main::getLoginUserInfo('userId');
                $ids[] = $userId;
                if (User::getExtraPower('dep','schoolContact',$userId,true)) { //有额外权限
                    $powerIds = $this->extraPower('schoolContact');
                    $ids = array_values(array_merge($ids,$powerIds));
                }
                if(!in_array($info->iCreateUserId,$ids) || !UserPower::checkUserPower('School_List_Contact_Edit') ){ //没有权限
                    $webArr['check'] = '<script>parent.$(\'#bt_modal_confirm\').hide();</script>';
                }
            }
        }

        $this->view->setVars($webArr);
    }

    /**
     * 绑定账号
     *
     * created by dale 2017125
     * modify by dale 20180324
     */
    public function bindAccountAction(){
        $this->view->pick('school_contact/bindAccount');
        Assets::importJs('js/school_contact/bindAccount.js');
        $iCUCId = $this->request->getQuery('iCUCId', 'int');
        if (!$iCUCId) {
            return $this->sendViewError('缺少联系人id！');
        }
        $contact = XhcustContact::findFirst($iCUCId);
        if (!$contact) {
            return $this->sendViewError('找不到联系人记录！');
        }
        if($contact->sPhoneNum == null){
            return $this->sendViewError('电话为空！');
        }
        if(!User::isAdmin()){ //额外权限查看
            $userId = Main::getLoginUserInfo('userId');
            $ids[] = $userId;
            if (User::getExtraPower('dep','schoolContact',$userId,true)) { //有额外权限
                $powerIds = $this->extraPower('schoolContact');
                $ids = array_values(array_merge($ids,$powerIds));
            }
            if(!in_array($contact->iCreateUserId,$ids)){ //没有权限
                return $this->sendViewError('没有权限！');
            }
        }

        $params = [
            'columns' => 'iUserId,sUserName,sLogonName,sSelfPhone,bDisable',
            'conditions' => 'sSelfPhone = :phoneNum: OR sLogonName = :phoneNum:',
            'bind' => ['phoneNum' => $contact->sPhoneNum]
        ];
        if ($contact->iUserId) {
            $params['conditions'] .= ' OR iUserId = :userId:';
            $params['bind']['userId'] = $contact->iUserId;
        }
        $userList = XhsysUser::find($params)->toArray();
        if (!$userList) {
            return $this->sendViewError('找不到联系人所属账号!');
        }
        if ($contact->iUserId) {
            foreach ($userList as $index => $user) {
                if ($contact->iUserId == $user['iUserId']) {
                    $userList[$index]['sUserName'] .= "<font style='color: red;'>(已绑定)</font>";
                }
            }
        }
        return $this->view->setVar('accountList', $userList);
    }

    /**
     * 保存绑定
     * @param bool $bind
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * create by dale 20180324
     */
    public function saveBindAction($bind = false)
    {
        try{
            $iCUCId = $this->request->getPost('iCUCId', 'int');
            $userId = $this->request->getPost('userId', 'int');
            if (!$iCUCId || !$userId) {
                return $this->sendErrorResponse(400,'缺少参数');
            }
            $contact = XhcustContact::findFirst($iCUCId);
            if (!$contact) {
                return $this->sendErrorResponse(500,'找不到联系人');
            }

            if(!User::isAdmin()){ //额外权限查看
                $nowUserId = Main::getLoginUserInfo('userId');
                $ids[] = $nowUserId;
                if (User::getExtraPower('dep','schoolContact',$nowUserId,true)) { //有额外权限
                    $powerIds = $this->extraPower('schoolContact');
                    $ids = array_values(array_merge($ids,$powerIds));
                }
                if(!in_array($contact->iCreateUserId,$ids) || !UserPower::checkUserPower('School_List_Contact_Bind') ){ //没有权限
                    return $this->sendErrorResponse(401,'没有权限！');
                }
            }

            if ($bind) {
                if ($userId != $contact->iUserId) {
                    return $this->sendErrorResponse(500,'该记录未关联');
                }
                $contact->iUserId = null;
            } else {
                $contact->iUserId = $userId;
            }
            if (!$contact->save()) {
                return $this->sendErrorResponse(500,'保存失败');
            }
            if($contact->iUserId != null){
                $user = XhsysUser::findFirst([
                    'columns'    => 'iSchoolId,iUserId,iUserType',
                    'conditions' => 'bDelete = 0 AND iUserId = :iUserId:',
                    'bind'       => ['iUserId' => $contact->iUserId]
                ]);
                if(!$user->iSchoolId){
                    return $this->sendErrorResponse(500,'设置学校权限时找不到学校');
                }
                if (!XhsysUserpower::createExtraRecord($userId,'school',['id'=>$user->iSchoolId,'all'=>false],['id'=>$user->iSchoolId,'all'=>false])) {
                    return $this->sendErrorResponse(500, '保存失败');
                }
                UserPower::delPowerCache('school', $userId);
            }

            return $this->sendSuccessResponse('保存成功');

        }catch (\Exception $e){
            return $this->sendErrorResponse(500,$e->getMessage());
        }
    }



    /**
     * 获取联系人信息(1条或者多条,过滤,搜索)
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface|string
     *
     *  created by dale 201787
     *  modify by dale 20180324
     */
    public function getContactDataAction()
    {
        if(!UserPower::checkUserPower('School_List_Contact')){
            return $this->sendErrorResponse(401,'没有权限！');
        }
        $iCUId = $this->request->getQuery('id');
        $iCUCId = $this->request->getPost('iCUCId');
        $key = $this->request->getPost('key');
        $sort = $this->request->getPost('sort', 'string');
        $order = $this->request->getPost('order', 'string');
        $enums = self::getEnums();
        $parameters = [
            'conditions' => 'bDelete=:bDelete:',
            'bind' => ['bDelete' => 0],
        ];
        if ($iCUCId) {
            $parameters['conditions'] .= "AND iCUCId=:iCUCId:";
            $parameters['bind'] = array_merge($parameters['bind'], array('iCUCId' => $iCUCId));
            $obj = XhcustContact::findFirst($parameters);
            return json_encode($obj->toArray());
        }
        if ($iCUId) {
            $parameters['conditions'] .= "AND iCUId=:iCUId:";
            $parameters['bind'] = array_merge($parameters['bind'], array('iCUId' => $iCUId));
        }
        if ($key) {
            $parameters['conditions'] .= "AND (sName like :key: OR sJob like :key:)";
            $parameters['bind'] = array_merge($parameters['bind'], array('key' => '%' . $key . '%'));
        }
        if ($sort && $order) {
            $parameters['order'] = $sort . " " . strtoupper($order);
        }
        $data = Main::runModelPaginator('Admin\Models\crm\XhcustContact', $parameters, true);
        $enums = ['sSubjects'=> XhsysEnum::getEnumByNodeName('学科') , 'sGrades' => XhsysEnum::getEnumByNodeName('年级'),
            'iDuty'=>XhsysEnum::getEnumByNodeName('学校职位'),'bCharge' => [1=>'是',0=>'否']];
        foreach ($data['rows'] as $index => $obj) {
            $data['rows'][$index]['bDefault']  = $enums['bDefault'][$obj['bDefault']];
            $data['rows'][$index]['sSubjects'] = $this->runEnums($obj['sSubjects'],$enums['sSubjects']);
            $data['rows'][$index]['sGrades']   = $this->runEnums($obj['sGrades'],$enums['sGrades']);
            $data['rows'][$index]['iDuty']     = $this->runEnums($obj['iDuty'],$enums['iDuty']);
            $data['rows'][$index]['bCharge']   = $this->runEnums($obj['bCharge'],$enums['bCharge']);
            $data['rows'][$index]['iUserId']   = $obj['iUserId'];
            if($obj['iUserId'] != null){
                $data['rows'][$index]['info'] = '<i class="fa fa-user" style="color:#2baab1;" title="'.$obj['iUserId'].'"></i>';
            }else{
                $data['rows'][$index]['info'] = '';
            }
        }
        Main::runUserNameById($data['rows'], 'iLastModifyUserId', true);
        Main::runUserNameById($data['rows'], 'iCreateUserId', true);
        return $this->response->setContent(json_encode($data, JSON_UNESCAPED_UNICODE));
    }

    /**
     * 处理枚举
     *
     * @param $fields
     * @param $enum
     * @return string
     * create by dale 20180308
     */
    public function runEnums($fields,$enum){
        $fields = array_values(array_filter(explode(',',$fields)));
        $arr = [];
        foreach ($fields as $field){
            $arr[] = $enum[$field];
        }
        return implode(',',$arr);
    }

    /**
     * 保存联系人信息(编辑,添加)
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * created by dale 2017/8/7
     * modify by dale 20180324
     */
    public function saveContactAction()
    {
        try{
            $iCUCId = $this->request->getPost('iCUCId', 'string');
            $iCUId = $this->request->getPost('iCUId', 'string') or die('缺少参数');
            $sSubjects = $this->request->getPost('sSubjects');
            $sGrades   = $this->request->getPost('sGrades');
            if ($iCUCId == null) {
                $obj = new XhcustContact();
                if(!UserPower::checkUserPower('School_List_Contact_Add')){
                    return $this->sendErrorResponse(401,'没有权限！');
                }
            } else {
                $obj = XhcustContact::findFirst($iCUCId);
                if(!User::isAdmin()){ //额外权限查看
                    $nowUserId = Main::getLoginUserInfo('userId');
                    $ids[] = $nowUserId;
                    if (User::getExtraPower('dep','schoolContact',$nowUserId,true)) { //有额外权限
                        $powerIds = $this->extraPower('schoolContact');
                        $ids = array_values(array_merge($ids,$powerIds));
                    }
                    if(!in_array($obj->iCreateUserId,$ids) || !UserPower::checkUserPower('School_List_Contact_Edit') ){ //没有权限
                        return $this->sendErrorResponse(401,'没有权限！');
                    }
                }
            }
            $obj->assign($this->request->getPost());
            //检查是否是第一条
            $check = XhcustContact::findFirst([
                'conditions' => 'bDelete=:bDelete: AND iCUId=:iCUId:',
                'bind' => ['bDelete' => 0, 'iCUId' => $iCUId],
            ]);
            if (!$check) {
                $obj->bDefault = 1;
            }
            $obj->sSubjects = isset($sSubjects) ? implode(',',$sSubjects) : null ;
            $obj->sGrades   = isset($sGrades)   ? implode(',',$sGrades)   : null ;
            $result = $obj->save();
            if ($result) {
                if ($obj->bDefault == 1) {
                    $info = XhcustInfo::findFirst([
                        'conditions' => 'bDelete=:bDelete: AND iCUId=:iCUId:',
                        'bind' => ['bDelete' => 0, 'iCUId' => $iCUId],
                    ]);
                    $info->sChargeName = $obj->sName;
                    $info->sChargePhone = $obj->sPhoneNum;
                    if ($info->save()) {
                        return json_encode($obj->toArray());
                    } else {

                        return $this->sendErrorResponse(500,'第一个默认联系人保存失败');
                    }
                }

                return $this->sendSuccessResponse('保存成功');
            } else {
                return $this->sendSuccessResponse(500,'保存失败');
            }
        }catch (\Exception $e){
            return $this->sendErrorResponse(500,$e->getMessage());
        }

    }

    /**
     * 改变默认
     *
     * @return string
     * created by dale 2017/8/10
     * modify by dale 20180324
     */
    public function changeDefaultAction()
    {
        try{
            $iCUCId = $this->request->getPost('iCUCId', 'string') ;
            $iCUId  = $this->request->getPost('iCUId', 'string') ;
            if(!$iCUCId || !$iCUId){
                return $this->sendErrorResponse(400,'缺少参数');
            }
            $contact = XhcustContact::findFirst([
                'conditions' => 'bDelete=:bDelete: AND iCUCId=:iCUCId:',
                'bind' => ['bDelete' => 0, 'iCUCId' => $iCUCId],
            ]);

            if(!User::isAdmin()){ //额外权限查看
                $nowUserId = Main::getLoginUserInfo('userId');
                $ids[] = $nowUserId;
                if (User::getExtraPower('dep','schoolContact',$nowUserId,true)) { //有额外权限
                    $powerIds = $this->extraPower('schoolContact');
                    $ids = array_values(array_merge($ids,$powerIds));
                }
                if(!in_array($contact->iCreateUserId,$ids) || !UserPower::checkUserPower('School_List_Contact_Edit') ){ //没有权限
                    return $this->sendErrorResponse(401,'没有权限！');
                }
            }

            if ($contact->bDefault == 1) {
                return $this->sendErrorResponse(400,'已经是默认联系人不需要在设置');
            }
            $this->db->begin(); //开启事务
            $objs = XhcustContact::find([
                'conditions' => 'bDelete=:bDelete: AND iCUId=:iCUId:',
                'bind' => ['bDelete' => 0, 'iCUId' => $iCUId],
            ]);
            if ($objs) {
                foreach ($objs as $obj) {
                    $obj->bDefault = 0;
                    if (!$obj->save()) {
                        $this->db->rollback();
                        return  $this->sendErrorResponse(500,'取消其他联系人失败');
                    }
                }
            }
            $contact->bDefault = 1;
            if (!$contact->save()) {
                $this->db->rollback();
                return $this->sendErrorResponse(500,'设置默认失败');
            }
            $info = XhcustInfo::findFirst([
                'conditions' => 'bDelete=:bDelete: AND iCUId=:iCUId:',
                'bind' => ['bDelete' => 0, 'iCUId' => $iCUId],
            ]);
            $info->sChargeName = $contact->sName;
            $info->sChargePhone = $contact->sPhoneNum;
            if (!$info->save()) {
                return $this->sendErrorResponse(500,'更新失败');
            }
            $this->db->commit();
            return $this->sendSuccessResponse('更新成功');
        }catch (\Exception $e){
            $this->db->rollback();
            return $this->sendErrorResponse(500,$e->getMessage());
        }

    }

    /**
     * 创建账号
     *
     * created by dale 2017126
     */
    public function createAccountAction(){
        try{
            $userName = $this->request->getPost('userName','string');
            $phoneNum = $this->request->getPost('phoneNum','string');
            $schoolId = $this->request->getPost('schoolId','int');
            if(!$userName || !$phoneNum){
                return $this->sendErrorResponse(400,'缺少参数');
            }
            $res = $this->createNewAccount($phoneNum,$userName,intval($schoolId));
            if($res){
                return $this->sendSuccessResponse('保存成功');
            }else{
                return $this->sendErrorResponse(500,'失败');
            }
        }catch (\Exception $e){
            return $this->sendErrorResponse(500,$e->getMessage());
        }

    }

    /**
     * 根据手机号，用户姓名创建账号
     *
     * @param $phoneNum
     * @param $staffName
     * @param string $pwd
     * @param $schoolId
     * @return bool
     * @throws \Exception
     *
     * create by ck 20171113
     */
    private function createNewAccount($phoneNum, $staffName,$schoolId, $pwd = '123456')
    {
        $user = new XhsysUser();
        $user->sLogonName   = $phoneNum;
        $user->sUserName    = $staffName;
        $user->sLogonPwd    = strtoupper(md5($pwd));
        $user->sSelfPhone   = $phoneNum;
        $user->iUserType    = 4;
        $user->iSchoolId    = $schoolId;
        return $user->insertAfterOld();
//        static $httpClient;
//        if (!$httpClient) {
//            $url = Main::getConfigByName('hrm')['registerUrl'];
//            if (!$url) {
//                throw new \Exception('缺少registerUrl配置');
//            }
//            $httpClient = new HttpClient($url);
//        }
//        $response = $httpClient->post('main/register-staff', ['K' => json_encode(['sSelfPhone' => $phoneNum, 'sUserName' => $staffName, 'sLogonPwd' => strtoupper(md5($pwd)),'iSchoolId'=>$schoolId,'iUserType'=>4])]);
//        if (!$response->isSuccess()) {
//            throw new \Exception('请求失败：' . $response->error);
//        }
//        $body = $response->toArray();
//        if ($body['R'] != 200) {
//            throw new \Exception($body['M'] ?: $response->body);
//        }
//        return true;
    }


    /**
     * 删除联系人信息
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * created by dale 2017/8/7
     * modify by dale 20180324
     */
    public function delContactAction()
    {
        try{
            $id = $this->request->getPost('id', 'string');

            if(!$id){
                return $this->sendErrorResponse(400,'缺少参数');
            }

            $obj = XhcustContact::findFirst([
                'conditions' => 'iCUCId = :id:',
                'bind' => ['id' => $id]
            ]);

            if(!User::isAdmin()){ //额外权限查看
                $nowUserId = Main::getLoginUserInfo('userId');
                $ids[] = $nowUserId;
                if (User::getExtraPower('dep','schoolContact',$nowUserId,true)) { //有额外权限
                    $powerIds = $this->extraPower('schoolContact');
                    $ids = array_values(array_merge($ids,$powerIds));
                }
                if(!in_array($obj->iCreateUserId,$ids) || !UserPower::checkUserPower('School_List_Contact_Del') ){ //没有权限
                    return $this->sendErrorResponse(401,'没有权限！');
                }
            }

            $obj->bDelete = 1;
            if(!$obj->save()){
                return $this->sendErrorResponse(500,'删除失败');
            }
            return $this->sendSuccessResponse('删除成功');
        }catch (\Exception $e){

            return $this->sendErrorResponse(500,$e->getMessage());
        }

    }


}